package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description:
 * @Version: V1.0
 */
@Configuration
@RestControllerAdvice
@Slf4j
public class ExceptionCatch {


    /**
     * 不可预知异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception ex) {
        // 记录日志
        log.error("ExceptionCatch ex: {}", ex);
        //ex.printStackTrace();
        // 发邮件/发短信
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "您的网络异常请稍后尝试");
    }

    /**
     * 可预知异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException ex) {
        // 记录日志
        log.error("CustomException ex: {}", ex);
        ex.printStackTrace();
        return ResponseResult.errorResult(ex.getAppHttpCodeEnum());
    }


    /**
     * 参数校验异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult custMethodException(MethodArgumentNotValidException ex) {
        // 记录日志
        log.error("CustomException ex: {}", ex);
        ex.printStackTrace();

        BindingResult result = ex.getBindingResult();
        String errormessage = result.getFieldError().getDefaultMessage();
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, errormessage);
    }

}
